import pickle, base64
from django.shortcuts import render
from rest_framework import status
from rest_framework.views import APIView
from rest_framework.response import Response
from django_redis import get_redis_connection
# Create your views here.


from .catSerializer import CartSerizlizer, CarSKUtSerizlizer, CartDeleteSerializer, CartSelectedSerializer
from . import constants
from goods.models import SKU


class catView(APIView):
    """
    购物车 视图
    """
    """
    def  perform_authentication(self, request) ：
            “”“重写父类的验证方法”“”
            pass
    它是具体认证的逻辑代码，用request.user来取值，如果不为None，说明验证通过
    """

    # sku_id
    # int
    # 是
    # 商品sku
    # id
    # count
    # int
    # 是
    # 数量
    # selected
    # bool
    # 是
    # 是否勾选，默认勾选

    def perform_authentication(self, request):
        """
        重写父类的验证方法，不在检查jwt，
        保证用户未登录情况下也能进行下面的请求方法
        不让他执行request的方法
        :param request:
        :return:
        """

        pass

    def post(self, request):
        """添加购物车"""
        # 调用序列化器校验数据
        serializer = CartSerizlizer(data=request.data)
        # 校验数据           #如果校验出错返回校验出错的字段
        serializer.is_valid(raise_exception=True)

        # 获取数据
        sku_id = serializer.validated_data.get("sku_id")
        count = serializer.validated_data.get("count")
        selected = serializer.validated_data.get("selected")

        # 尝试对请求的与用户进行验证
        try:
            user = request.user
        except Exception:
            # 验证失败，用户登陆
            user = None

        if user is not None and user.is_authenticated:
            # 用户已登陆，在redis中保存
            redis_conn = get_redis_connection("cart")

            # 创建管道
            p1 = redis_conn.pipeline()
            # 记录购物车商品数量
            p1.hincrby("cart_%s" % user.id, sku_id, count)
            # 记录购物车的勾选项
            # 勾选
            if selected:
                p1.sadd("cart_selected_%s" % user.id, sku_id)
            # 提交
            p1.execute()

            return Response(serializer.data, status=status.HTTP_200_OK)


        else:
            # 用户未登录，在cookie中保存
            # {
            #     1001: { "count": 10, "selected": true},
            #     ...
            # }
            # 使用pickle序列化购物车数据，pickle操作的是bytes类型
            # 獲取connkie中的數據
            cart = request.COOKIES.get("cart")

            if cart is None:
                cart = {}

            else:
                cart = pickle.loads(base64.b64decode(cart))
            # 獲取當前用戶的sku_id
            sku_dict = cart.get(sku_id)
            # 並獲取當前用戶的數量加到

            # 其實我真不知道+=與有什麼作用
            if sku_dict:
                count += int(sku_dict.get['count'])
            # 原樣返回
            cart["sku_di"] = {
                "count": count,
                "selected": selected
            }

            cookie_cart = base64.b64encode(pickle.dumps(cart)).decode()
            response = Response(serializer.data, status=status.HTTP_201_CREATED)

            # 设置购物车的cookie
            # 需要设置有效期，否则是临时cookie
            response.set_cookie('cart', cookie_cart, max_age=constants.CART_COOKIE_EXPIRES)
            return response

    def get(self, request):
        """
        獲取購物車
        :param request:
        :return:
        """
        try:
            user = request.user
        except Exception:
            user = None

        if user is not None and user.is_authenticated():
            # 用戶已登陸
            redis_conn = get_redis_connection("cart")
            redis_cart = redis_conn.hgetall("cart_%s" % user.id)
            redis_cart_selected = redis_conn.smembers("cart_selected_%s" % user.id)
            print("獲取購物車%s" % redis_cart_selected)
            """
            redis_cart中的數據是分散，我們可以重新組裝數據，格式與cooke中的購物車一樣，這樣的話我們可以在返回代碼的
            時候公用一條代碼
            """
            cart = {}
            for sku_id, count in redis_cart.items():
                cart[int(sku_id)] = {
                    "count": int(count),
                    "selected": sku_id in redis_cart_selected

                }

        else:
            # 用戶爲登陸，從cooken中獲取
            cart = request.COOKIES.get("cart")
            if cart is not None:
                cart = pickle.loads(base64.b64decode(cart))

            else:
                cart = {}
        print(cart.keys())

        # 便利處理購物車的數據,獲取前段的其他數據
        skus = SKU.objects.filter(id__in=cart.keys())

        # 這段查詢到的是什麼

        print("%s_sku" % skus)
        for sku in skus:
            sku.count = cart[sku.id]["count"]
            sku.selected = cart[sku, id]["selected"]

        serializer = CarSKUtSerizlizer(skus, many=True)

        return Response(serializer.data)

    def put(self, request):
        """更改購物車中的商品"""

        serializer = CartSerizlizer(data=request.data)

        serializer.is_valid(raise_exception=True)

        sku_id = serializer.validated_data.get("sku_id")
        count = serializer.validated_data.get("count")
        selected = serializer.validated_data.get("selected")

        # 對請求用戶驗證
        try:
            user = request.user

        except Exception:
            # 驗證失敗用戶未登錄
            user = None

        if user is not None and user.is_authenticated:
            # 用戶已登陸在redis中保存
            redis_conn = get_redis_connection("cart")

            p1 = redis_conn.pipeline()
            p1.hest("cart_%s" % user.id, sku_id, count)
            if selected:
                p1.sadd("cart_selected_%s" % user.id, sku_id)
            else:
                p1.srem("cart_selected_%s" % user.id, sku_id)

            p1.execute()

            return Response(selected.data)

        else:
            # 用戶未登錄，在cookie中保存
            # 使用pickle序列化購物車數據，pickle 是byes數據
            # 獲取cookie中的購車數據

            cart = request.COOKIES.get("cart")

            if cart is not None:
                cart = pickle.loads(base64.b64decode(cart))
            else:
                cart = {}

            cart[sku_id] = {
                "count": count,
                "selected": selected,
            }

            cookie_cart = base64.b64encode(pickle.dumps(cart)).decode()

            response = Response(serializer.data)
            # 設置購物車cookie,佛則是臨時

            response.set_cookie("cart", cookie_cart, max_age=constants.CART_COOKIE_EXPIRES)

            return response

    def delete(self, request):
        """
        刪除購物車
        :param request:
        :return:
        """

        serializer = CartDeleteSerializer(data=request.data)

        serializer.is_valid(raise_exception=True)

        sku_id = serializer.validated_data['sku_id']

        try:
            user = request.user
        except Exception:
            user = None

        if user is not None and user.is_authenticated:
            # 用戶易登陸在redis 中刪除
            redis_conn = get_redis_connection("cart")

            p1 = redis_conn.pipeline()
            p1.hdel("cart_%s" % user.id, sku_id)
            p1.srem("cart_selected_%s" % user.id, sku_id)
            p1.execute()

            return Response(status=status.HTTP_200_OK)

        else:

            response = Response(serializer.data, status=status.HTTP_200_OK)
            # 如果未登錄更改cooki中的數據
            cart = request.COOKIES.get("cart")

            # 判斷不爲空，需要對前段數據解碼
            if cart is not None:
                cart = pickle.loads(base64.b64decode(cart))
                print(cart)
            for sku_id in cart:
                del cart[sku_id]

                cookie_cart = base64.b16encode(pickle.dumps(cart)).decode()

                # 設置購物車的cookie
                # 需要設置有效期佛則是臨時cookie

                response.set_cookie("cart", cookie_cart, max_age=constants.CART_COOKIE_EXPIRES)

            return response


class CartSelectAllView(APIView):
    """全選商品"""

    def perform_authentication(self, request):
        """
        重寫父類方法
        :param request:
        :return:
        """

        pass

    def put(self, request):
        serializer = CartSelectedSerializer(data=request.data)

        serializer.is_valid(raise_exception=True)

        selected = serializer.validated_data["selected"]

        # 獲取用戶是否登陸
        try:
            user = request.user
        except Exception:
            # 用戶未登錄
            user = None

        if user is not None and user.is_authenticated:
            # 用戶已登陸
            redis_conn = get_redis_connection("cart")
            p1 = redis_conn.pipeline()
            # 獲取redis中的所有商品sku_id
            cart=p1.hgetall("cart_%s" % user.id)
            #獲取所有的sku_id
            sku_id_list=cart.keys()
            if selected:
                redis_conn.sadd("cart_selected_%s",user.id,*sku_id_list)

            else:
                redis_conn.srem("cart_selected_%s",user.id,*sku_id_list)
            return Response({"massage":"ok"})

        else:

            # 用戶未登錄
            cart=request.COOKIES.get("cart")

            response=Response({"massage":"ok"})

            if cart is not None:
                cart=pickle.loads(base64.b64decode(cart))

                for sku_id in cart:
                    cart[sku_id]["selected"]=selected

                cookiie_cart=base64.b16encode(pickle.dumps(cart))

                #設置購物車cookie
                #需要設置有效期佛則是臨時cookie

                response.set_cookie("cart",cookiie_cart,max_age=constants.CART_COOKIE_EXPIRES)

            return response









